from scipy.stats import f

# 平均值
l = [1,2,3,4,5,6,7,8,9]
print(sum(l)/len(l))

# 中位数:排在中间的数字
def get_median(l):
  data = sorted(l)
  size = len(data)
  median = 0
  if size % 2 == 0:
    median = (data[size//2-1] + data[size//2]) / 2
  else:
    median = data[size//2]
  return median

print(get_median([1,2,3,4,5,6]))


# 众数:出现次数最多的数字
def get_mode(arr):
  arr_appear = dict((a, arr.count(a)) for a in arr)
  mode = []
  if max(arr_appear.values()) > 1:
    for k, v in arr_appear.items():
      if v == max(arr_appear.values()):
        mode.append(k)
  return mode

print(get_mode([1,2,2,3,3,4,3,4,3,4,5,5,1,4,5,5]))


# 极差:最大值与最小值之差
def get_range(arr):
  return max(arr) - min(arr)

l = [1,2,3,4,5,6,7,8,9]
print(get_range(l))

# 方差:平均值与每个数据点的距离的平方之和
def get_variance(arr):
  mean = sum(arr) / len(arr)
  return sum([(a - mean) ** 2 for a in arr]) / len(arr)

print(get_variance([1,2,3,4,5,6,7]))

def get_sample_variance(arr):
  mean = sum(arr) / len(arr)
  return sum([(a - mean) ** 2 for a in arr]) / (len(arr) - 1)

# 标准差:方差的平方根
def get_std(arr):
  return get_variance(arr) ** 0.5

print(get_std([1,2,3,4,5,6,7]))




# 假设检验:方差分析
"""
一、问题场景:比较三种肥料对小麦株高的影响
农技站想回答：
H0：μA＝μB＝μC（三种肥料下小麦平均株高相等）
H1：至少有一种肥料的平均株高不同
"""
# 样本数据
fa = [22,21,23,20,22,21]
fb = [26,27,28,25,29,26]
fc = [24,25,23,26,24,25]
# 均值
xa = sum(fa) / len(fa)
xb = sum(fb) / len(fb)
xc = sum(fc) / len(fc)
print(xa, xb, xc)
# 样本方差
va = get_sample_variance(fa)
vb = get_sample_variance(fb)
vc = get_sample_variance(fc)
print(va, vb, vc)
# 显著性水平
alpha = 0.05
# 总平均
x = round((xa + xb + xc) / 3,3)
print(x)
# 组间平方和
ssb = len(fa) * ((xa - x) ** 2 + (xb - x) ** 2 + (xc - x) ** 2)
# 组内平方和
ssw = (len(fa)-1) * va + (len(fb)-1) * vb + (len(fc)-1) * vc
print(ssb, ssw)
# 统计自由度
dfb = 3 - 1
dfw = len(fa) + len(fb) + len(fc) - 3
print(dfb, dfw)
# 组间均方
msb = ssb / dfb
# 组内均方
msw = ssw / dfw
print(msb, msw)
# 计算F值
fv = msb / msw
print(fv)
# 根据自由度查F分布
f_crit = f.ppf(1-alpha, dfb, dfw)
print(f_crit)
# 判断H0是否被拒绝
if fv > f_crit:
  print('拒绝H0，有差异')
else:
  print('接受H0，无差异')
